package com.theexceptions.todo.controller;

import com.theexceptions.todo.model.DatabaseHelper;
import com.theexceptions.todo.model.IPersister;
import com.theexceptions.todo.model.User;

/**
 * A controller that handles all user login operations.
 * 
 * @author Justian Meyer and JD Reddaway
 */
public abstract class LoginController extends Controller {

	//TODO change to enums? http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html
	public static final int LOGIN_SUCCESS = 1;
	public static final int WRONG_PASSWORD = 0;
	public static final int INVALID_USERNAME = -1;

	/**
	 * Attempts to log a user into the system by checking whether or not the
	 * provided username and password correctly correspond to information in the
	 * database and returns an integer detailing the success of the action.
	 * 
	 * @param username Username provided by the user
	 * @param password Password provided by the user
	 * @return INVALID_USERNAME if username not found in database,
	 *         WRONG_PASSWORD if password does not match password in database,
	 *         LOGIN_SUCCESS if both credentials match
	 */
	public static int loginUser(String username, String password) {
		IPersister dh = new DatabaseHelper(context);
		User user = dh.retrieveUser(username);
		
		if (user == User.EMPTY_USER) {
			return INVALID_USERNAME;
		} else {
			if (user.checkPassword(password)) {
				currentUser = user;
				return LOGIN_SUCCESS;
			} else {
				return WRONG_PASSWORD;
			}
		}
	}
}
